package de.krischan.udelhoven;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Properties;

public class MocklocServer implements Runnable {
	private int port;
	private Location location;
	
	MocklocServer(Location location) {
		this.location = location;
		Properties properties = new Properties();
		try {
			properties.load(new BufferedInputStream(new FileInputStream("settings.properties")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.port = Integer.parseInt(properties.getProperty("port"));
	}
	
	public void run(){
		DatagramSocket serverSocket = null;
		try {
			serverSocket = new DatagramSocket(this.port);
		} catch (SocketException e1) {
			e1.printStackTrace();
		}
		byte[] receiveData = new byte[1024];
		byte[] sendData = new byte[1024];
		while (true) {
			DatagramPacket receivePacket = new DatagramPacket(receiveData,
					receiveData.length);
			try {
				serverSocket.receive(receivePacket);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			String sentence = new String(receivePacket.getData());
			System.out.println("RECEIVED: " + sentence);
			
			InetAddress IPAddress = receivePacket.getAddress();
			int port = receivePacket.getPort();
			
			String loc = this.location.getLat() + ";" + this.location.getLng();
			sendData = loc.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData,
					sendData.length, IPAddress, port);
			try {
				serverSocket.send(sendPacket);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String args[]) {
		Thread server = new Thread(new MocklocServer(new Location()));
		server.start();
	}
}
